//编写一个函数来查找字符串数组中的最长公共前缀。 
//
// 如果不存在公共前缀，返回空字符串 ""。 
//
// 
//
// 示例 1： 
//
// 
//输入：strs = ["flower","flow","flight"]
//输出："fl"
// 
//
// 示例 2： 
//
// 
//输入：strs = ["dog","racecar","car"]
//输出：""
//解释：输入不存在公共前缀。 
//
// 
//
// 提示： 
//
// 
// 0 <= strs.length <= 200 
// 0 <= strs[i].length <= 200 
// strs[i] 仅由小写英文字母组成 
// 
// Related Topics 字符串 
// 👍 1416 👎 0

package com.leetcode.editor.cn;

//Java：最长公共前缀
class P14LongestCommonPrefix {
    public static void main(String[] args) {
        Solution solution = new P14LongestCommonPrefix().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return "";
            }
            //1.横向扫描
            String s = strs[0];
            for (int i = 1; i < strs.length; i++) {
                if (s.length() == 0) {
                    return "";
                }
                s = commonPrefix(s, strs[i]);
            }
            return s;
            //2.归并
//            return longestCommonPrefix(strs, 0, strs.length - 1);
        }

        private String longestCommonPrefix(String[] strs, int start, int end) {
            if (end == start) {
                return strs[start];
            }
            int mid = (start + end) / 2;
            String left = longestCommonPrefix(strs, start, mid);
            String right = longestCommonPrefix(strs, mid + 1, end);
            return commonPrefix(left, right);
        }

        private String commonPrefix(String ans, String str) {
            char[] chars1 = ans.toCharArray();
            char[] chars2 = str.toCharArray();
            int len = Math.min(chars1.length, chars2.length);
            for (int i = 0; i < len; i++) {
                if (chars1[i] != chars2[i]) {
                    return ans.substring(0, i);
                }
            }
            return ans.substring(0, len);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}